import { messageBox } from '../libs/WeisonUI/Modal/index';
import { getScrolled, getViewportSize, getElementPosition } from './tools'
import dayjs from 'dayjs'
function debounce(cb, time, triggleNow) {
    let t = null;
    const debounced = function () {
        const args = arguments;
        t && clearTimeout(t);
        if (triggleNow) {
            let exec = !t;//刚进来就解锁
            t = setTimeout(() => t = null, time);//重新上锁，一秒后不再触发就解锁
            exec && cb.apply(this, args)
        } else { t = setTimeout(() => cb.apply(this, args), time) }
    }
    //加个静态方法有需要时可调用强制取消防抖
    debounced.remove = function () {
        clearTimeout(t);
        t = null;
    }
    return debounced;
}

//时间戳版本
function throttle(cb, time, tip) {
    let last = 0;
    return function () {
        const args = arguments,
            now = Date.now();
        if (now - last >= time) {
            cb.apply(this, args);
            last = now;
        } else {
            tip && messageBox(tip, 2000);
            return;
        }
    }
}

function formatTime(time) {
    return dayjs(time).format("YYYY年MM月DD日HH时mm分");
};
function formatDay(time) {
    return dayjs(time).format("YYYY年MM月DD日");
};



function imgLazyLoad(imgList) {
    const lazyImgs = document.getElementsByClassName("img-container");
    const len = lazyImgs.length;
    const sTop = getScrolled().top,
        cHeight = getViewportSize().height;
    for (let i = 0; i < len; i++) {
        const imgItem = lazyImgs[i],
            imgOffset = getElementPosition(imgItem).top;
        if (cHeight + sTop > imgOffset) {
            imgItem.innerHTML = imgList[i];
        }
    }
    // lazyImgs.forEach((item, index) => {
    //     const imgOffset = getElementPosition(item).top;
    //     if (imgOffset < cHeight + sTop) {
    //         lazyImgs[index].innerHTML = imgList[index];
    //         n++;
    //     }
    // })


}


export {
    debounce,
    throttle,
    formatTime,
    formatDay,
    imgLazyLoad
}